<template>
  <div class="satellite-cloud-container">
    <!-- 卫星云图控制组件 -->
    <div class="satellite-cloud-control" :class="{ expanded: isPanelExpanded }">
      <!-- 控制图标 -->
      <div class="control-icon" @click="togglePanel" v-if="!isPanelExpanded" title="卫星云图">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"></path>
          <path d="M12 13v1"></path>
          <path d="M12 17h.01"></path>
        </svg>
      </div>

      <!-- 卫星云图控制面板 -->
      <div class="satellite-cloud-control-panel" v-if="isPanelExpanded">
        <div class="panel-header">
          <h3>卫星云图</h3>
          <div class="close-btn" @click="togglePanel">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M18 6L6 18M6 6l12 12"></path>
            </svg>
          </div>
        </div>
        
        <!-- 图层开关 -->
        <div class="control-section">
          <div class="legend-item checkbox-label" @click="toggleShow('isLayerVisible')">
            <input type="checkbox" v-model="isLayerVisible" class="legend-checkbox">
            <span class="checkmark"></span>
            <span class="legend-text">显示卫星云图</span>
          </div>
        </div>
        
        <!-- 播放控制 -->
        <div class="control-section">
          <div class="playback-controls">
            <button class="control-btn" @click="rewind" :disabled="!isLayerVisible || isLoading">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polygon points="11 19 2 12 11 5 11 19"></polygon>
                <polygon points="22 19 13 12 22 5 22 19"></polygon>
              </svg>
              快退
            </button>
            <button class="control-btn" @click="togglePlay" :disabled="!isLayerVisible || isLoading">
              <svg v-if="!isPlaying" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polygon points="5 3 19 12 5 21 5 3"></polygon>
              </svg>
              <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="6" y="4" width="4" height="16"></rect>
                <rect x="14" y="4" width="4" height="16"></rect>
              </svg>
              {{ isPlaying ? '暂停' : '播放' }}
            </button>
            <button class="control-btn" @click="fastForward" :disabled="!isLayerVisible || isLoading">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polygon points="13 5 22 12 13 19 13 5"></polygon>
                <polygon points="2 5 11 12 2 19 2 5"></polygon>
              </svg>
              快进
            </button>
          </div>
        </div>
        
        <!-- 时间轴 -->
        <div class="control-section">
          <div class="time-display" v-if="currentTimePoint">{{ formatTime(currentTimePoint.time) }}</div>
          <div class="time-display" v-else>加载中...</div>
          <input 
            type="range" 
            v-model.number="currentIndex" 
            :min="0" 
            :max="timePoints.length - 1" 
            @input="updateImageByIndex"
            :disabled="!isLayerVisible || isLoading || timePoints.length === 0"
            class="time-slider"
          >
          <div class="frame-info">
            <span>{{ currentIndex + 1 }} / {{ timePoints.length }}</span>
          </div>
        </div>
        
        <!-- 播放速度调整 -->
        <div class="control-section">
          <div class="speed-control">
            <label class="speed-label">播放速度: {{ (1000 / playbackSpeed).toFixed(1) }}x</label>
            <input 
              type="range" 
              v-model.number="playbackSpeed" 
              :min="200" 
              :max="2000" 
              :step="100"
              @input="updatePlaybackSpeed"
              :disabled="!isLayerVisible || isLoading"
              class="speed-slider"
            >
          </div>
        </div>
        
        <!-- 透明度调整 -->
        <div class="control-section">
          <div class="opacity-control">
            <label class="opacity-label">透明度: {{ Math.round(opacity * 100) }}%</label>
            <input 
              type="range" 
              v-model.number="opacity" 
              :min="0" 
              :max="1" 
              :step="0.1"
              @input="updateOpacity"
              :disabled="!isLayerVisible || isLoading"
              class="opacity-slider"
            >
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div class="control-section" v-if="isLoading">
          <div class="loading-indicator">
            <svg class="loading-spinner" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" stroke-dasharray="50" stroke-dashoffset="0"></circle>
            </svg>
            <span>加载中...</span>
          </div>
        </div>
        
        <!-- 预加载状态 -->
        <div class="control-section" v-if="isPreloading">
          <div class="preloading-indicator">
            <svg class="loading-spinner" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" stroke-dasharray="50" stroke-dashoffset="0"></circle>
            </svg>
            <span>预加载中...</span>
          </div>
          <div class="preload-progress-bar">
            <div class="preload-progress" :style="{ width: `${preloadProgress}%` }"></div>
          </div>
        </div>
        
        <!-- 错误信息 -->
        <div class="control-section" v-if="loadError">
          <div class="error-message">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="12" cy="12" r="10"></circle>
              <line x1="12" y1="8" x2="12" y2="12"></line>
              <line x1="12" y1="16" x2="12.01" y2="16"></line>
            </svg>
            <span>{{ loadError }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue';
import { SatelliteCloudUtils } from '../utils/SatelliteCloudUtils';

const props = defineProps({
  viewer: {
    type: Object,
    required: true
  }
});

// 状态管理
const isPanelExpanded = ref(false);
const satelliteUtils = ref(null);
const isLoading = ref(false);
const isPreloading = ref(false);
const isLayerVisible = ref(false);
const isPlaying = ref(false);
const currentIndex = ref(0);
const opacity = ref(0.8);
const playbackSpeed = ref(1000); // 播放速度（毫秒/帧）
const timePoints = ref([]);
const currentTimePoint = ref(null);
const loadError = ref(null);
const preloadProgress = ref(0);

// 切换面板展开/折叠状态
const togglePanel = () => {
  isPanelExpanded.value = !isPanelExpanded.value;
  if (isPanelExpanded.value) {
    // 面板展开时加载卫星云图数据
    loadSatelliteData();
  } else {
    // 面板折叠时清理资源
    clearSatellite();
  }
};

// 切换显示选项
const toggleShow = (option) => {
  if (option === 'isLayerVisible') {
    isLayerVisible.value = !isLayerVisible.value;
    if (isLayerVisible.value) {
      // 显示图层
      showSatelliteLayer();
    } else {
      // 隐藏图层
      hideSatelliteLayer();
    }
  }
};

// 加载卫星云图数据
const loadSatelliteData = async () => {
  if (isLoading.value || timePoints.value.length > 0) return;
  
  isLoading.value = true;
  loadError.value = null;
  
  try {
    // 初始化卫星云图工具类
    if (!satelliteUtils.value) {
        satelliteUtils.value = new SatelliteCloudUtils(props.viewer);
        // 订阅帧回调，使组件的 currentIndex/currentTimePoint 随播放同步
        satelliteUtils.value.onFrame = (index, timePoint) => {
          currentIndex.value = index;
          currentTimePoint.value = timePoint;
        };
    }
    
    // 获取卫星云图数据
    const data = await satelliteUtils.value.fetchSatelliteData();
    
    // 解析数据
    const parsedData = satelliteUtils.value.parseSatelliteData(data);
    timePoints.value = parsedData.timePoints;
    
    // 创建卫星云图图层
    satelliteUtils.value.createSatelliteLayer();
    
    // 更新当前时间点
    currentTimePoint.value = satelliteUtils.value.getCurrentTimePoint();
    
    // 设置透明度
    satelliteUtils.value.setOpacity(opacity.value);
    
    // 初始隐藏图层，等待用户勾选
    hideSatelliteLayer();
    
    // 开始预加载图片
    preloadImages();
  } catch (error) {
    console.error('加载卫星云图失败:', error);
    loadError.value = error.message;
  } finally {
    isLoading.value = false;
  }
};

// 预加载图片
const preloadImages = async () => {
  if (!satelliteUtils.value || timePoints.value.length === 0) return;
  
  isPreloading.value = true;
  preloadProgress.value = 0;
  
  try {
    // 设置播放速度
    satelliteUtils.value.setPlaybackSpeed(playbackSpeed.value);
    
    // 开始预加载
    await satelliteUtils.value.preloadAllImages();
  } catch (error) {
    console.error('预加载图片失败:', error);
  } finally {
    isPreloading.value = false;
    preloadProgress.value = 100;
  }
};

// 显示卫星云图图层
const showSatelliteLayer = () => {
  if (satelliteUtils.value) {
    satelliteUtils.value.showLayer();
  }
};

// 隐藏卫星云图图层
const hideSatelliteLayer = () => {
  if (satelliteUtils.value) {
    satelliteUtils.value.hideLayer();
  }
};

// 清理卫星云图资源
const clearSatellite = () => {
  if (satelliteUtils.value) {
      satelliteUtils.value.destroy();
      // 解除回调引用
      satelliteUtils.value.onFrame = null;
      satelliteUtils.value = null;
  }
  timePoints.value = [];
  currentTimePoint.value = null;
  currentIndex.value = 0;
  isPlaying.value = false;
  isLayerVisible.value = false;
};

// 切换播放状态
const togglePlay = () => {
  if (!satelliteUtils.value) return;
  
  if (isPlaying.value) {
    // 暂停播放
    satelliteUtils.value.pauseAnimation();
    isPlaying.value = false;
  } else {
    // 开始播放
    satelliteUtils.value.playAnimation();
    isPlaying.value = true;
  }
};

// 快进
const fastForward = () => {
  if (!satelliteUtils.value) return;
  
  satelliteUtils.value.fastForward();
  currentIndex.value = satelliteUtils.value.currentIndex;
  currentTimePoint.value = satelliteUtils.value.getCurrentTimePoint();
};

// 快退
const rewind = () => {
  if (!satelliteUtils.value) return;
  
  satelliteUtils.value.rewind();
  currentIndex.value = satelliteUtils.value.currentIndex;
  currentTimePoint.value = satelliteUtils.value.getCurrentTimePoint();
};

// 根据索引更新卫星云图
const updateImageByIndex = () => {
  if (!satelliteUtils.value) return;
  
  const timePoint = satelliteUtils.value.updateSatelliteImage(currentIndex.value);
  currentTimePoint.value = timePoint;
};

// 更新透明度
const updateOpacity = () => {
  if (!satelliteUtils.value) return;
  
  satelliteUtils.value.setOpacity(opacity.value);
};

// 更新播放速度
const updatePlaybackSpeed = () => {
  if (!satelliteUtils.value) return;
  
  satelliteUtils.value.setPlaybackSpeed(playbackSpeed.value);
};

// 格式化时间显示
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  
  const date = new Date(timeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 组件挂载时初始化
onMounted(() => {
  // 初始化卫星云图工具类
  satelliteUtils.value = new SatelliteCloudUtils(props.viewer);
});

// 组件卸载时清理
onBeforeUnmount(() => {
  clearSatellite();
});
</script>

<style scoped>
.satellite-cloud-container {
  position: absolute;
  top: 140px;
  right: 20px;
  z-index: 10;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
}

.satellite-cloud-control {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
  transition: all 0.3s ease;
}

.control-icon {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow:
    0 8px 32px rgba(77, 171, 247, 0.4),
    0 0 0 1px rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  color: white;
}

.control-icon:hover {
  transform: translateY(-2px);
  box-shadow:
    0 12px 40px rgba(77, 171, 247, 0.6),
    0 0 0 1px rgba(255, 255, 255, 0.2);
}

.satellite-cloud-control-panel {
  color: white;
  background: linear-gradient(135deg, rgba(15, 23, 42, 0.15) 0%, rgba(30, 41, 59, 0.15) 100%);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 10px;
  padding: 12px;
  max-width: 240px;
  opacity: 0;
  transform: translateY(20px) scale(0.95);
  pointer-events: none;
  transition: all 0.3s ease;
  box-shadow:
    0 10px 25px rgba(0, 0, 0, 0.15),
    0 0 0 1px rgba(255, 255, 255, 0.08);
}

.satellite-cloud-control.expanded .satellite-cloud-control-panel {
  opacity: 1;
  transform: translateY(0) scale(1);
  pointer-events: all;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.15);
}

.panel-header h3 {
  margin: 0;
  color: white;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 0.5px;
  padding-bottom: 0;
  border-bottom: none;
}

.close-btn {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.7);
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.control-section {
  margin-bottom: 16px;
}

/* 图例样式 */
.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.9);
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 6px;
  color: rgba(255, 255, 255, 0.95);
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 11px;
  font-weight: 500;
  width: calc(100% - 16px);
}

.checkbox-label:hover {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.2);
}

.legend-checkbox {
  display: none;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  position: relative;
  transition: all 0.2s ease;
}

.checkbox-label input:checked + .checkmark {
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  border-color: transparent;
}

.checkbox-label input:checked + .checkmark::after {
  content: '';
  position: absolute;
  left: 5px;
  top: 2px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.legend-text {
  flex: 1;
}

/* 播放控制样式 */
.playback-controls {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.control-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 10px;
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 6px;
  color: rgba(255, 255, 255, 0.95);
  font-size: 11px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.control-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  border-color: rgba(255, 255, 255, 0.2);
  color: white;
  box-shadow: 0 4px 15px rgba(77, 171, 247, 0.3);
  transform: translateX(2px);
}

.control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 时间轴样式 */
.time-display {
  text-align: center;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 8px;
  padding: 4px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
}

.time-slider {
  width: 100%;
  height: 4px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 2px;
  outline: none;
  -webkit-appearance: none;
  appearance: none;
  margin-bottom: 4px;
}

.time-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 12px;
  height: 12px;
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(77, 171, 247, 0.4);
}

.time-slider::-moz-range-thumb {
  width: 12px;
  height: 12px;
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  border-radius: 50%;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 6px rgba(77, 171, 247, 0.4);
}

.time-slider:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.frame-info {
  text-align: center;
  font-size: 10px;
  color: rgba(255, 255, 255, 0.7);
}

/* 透明度控制样式 */
.opacity-control {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.opacity-label {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.9);
  text-align: center;
}

.opacity-slider {
  width: 100%;
  height: 4px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 2px;
  outline: none;
  -webkit-appearance: none;
  appearance: none;
}

.opacity-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 12px;
  height: 12px;
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(77, 171, 247, 0.4);
}

.opacity-slider::-moz-range-thumb {
  width: 12px;
  height: 12px;
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  border-radius: 50%;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 6px rgba(77, 171, 247, 0.4);
}

.opacity-slider:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 加载状态样式 */
.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 8px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.9);
}

.loading-spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 播放速度控制样式 */
.speed-control {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.speed-label {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.9);
  text-align: center;
}

.speed-slider {
  width: 100%;
  height: 4px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 2px;
  outline: none;
  -webkit-appearance: none;
  appearance: none;
}

.speed-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 12px;
  height: 12px;
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(77, 171, 247, 0.4);
}

.speed-slider::-moz-range-thumb {
  width: 12px;
  height: 12px;
  background: linear-gradient(135deg, #4dabf7 0%, #339af0 100%);
  border-radius: 50%;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 6px rgba(77, 171, 247, 0.4);
}

.speed-slider:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 预加载状态样式 */
.preloading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 8px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 8px;
}

.preload-progress-bar {
  width: 100%;
  height: 4px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 2px;
  overflow: hidden;
}

.preload-progress {
  height: 100%;
  background: linear-gradient(90deg, #4dabf7 0%, #339af0 100%);
  border-radius: 2px;
  transition: width 0.3s ease;
}

/* 错误信息样式 */
.error-message {
  color: #ff6b6b;
  font-size: 11px;
  text-align: center;
  padding: 8px;
  background: rgba(255, 107, 107, 0.1);
  border: 1px solid rgba(255, 107, 107, 0.2);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}
</style>